#include "workCmd.h"

//客户端队列操作
int initClientQueue(clientQueue_t *pclientQueue){
    pclientQueue->timer = 0;
    memset(pclientQueue->clientFd,-1,sizeof(pclientQueue->clientFd));
    memset(pclientQueue->idex,0,sizeof(pclientQueue->idex));
    for(int i = 0;i < TIME_SLICE; ++i){
        pclientQueue->timeOut[i].head = NULL;
        pclientQueue->timeOut[i].tail = NULL;
        pclientQueue->timeOut[i].size = 0;
    }
    return 1;
}

int addFd(int netFd,clientQueue_t *pclientQueue){
    slotNode_t *newSlot = (slotNode_t *)calloc(1,sizeof(slotNode_t));
    newSlot->netFd = netFd;
    //记录超时时间点，取余会影响精度
    pclientQueue->idex[netFd] = (pclientQueue->timer + TIME_SLICE -1);
    //记录索引
    int index = (pclientQueue->timer + TIME_SLICE -1) % TIME_SLICE;
    ++pclientQueue->timeOut[index].size;
    if(pclientQueue->timeOut[index].head == NULL){
        pclientQueue->timeOut[index].head = newSlot;
        pclientQueue->timeOut[index].tail = newSlot;
    }
    else{
        pclientQueue->timeOut[index].tail->next = newSlot;
    }
    return 1;
}
int delFd(int netFd,clientQueue_t *pclientQueue){
    int abs_time = pclientQueue->idex[netFd];
    if(abs_time == 0) return -1;

    int index = abs_time % TIME_SLICE;
    pclientQueue->idex[netFd] = 0;

    slotNode_t *cur = pclientQueue->timeOut[index].head;
    slotNode_t *pre = cur;

    if(cur == NULL){
        return -1;
    }
    if(cur->netFd == netFd){
        pclientQueue->timeOut[index].head = cur->next;
        free(cur);
        --pclientQueue->timeOut[index].size;
    }else{
        while(cur != NULL){
            if(cur->netFd == netFd){
                pre->next = cur->next;
                free(cur);
                --pclientQueue->timeOut[index].size;
                break;
            }
            pre = cur;
            cur = cur->next;
        }
    }
    return 1;
}

